import { sequelize, Group, UserGroup, User, Task } from '../models'
import { generateAvatar } from './group_avatar_mq'
import _ from 'lodash'
import fdb from '../lib/fdb'

/**
 * First find or create a group using openGId
 * Then check if user exists with userId
 * at last find or create a user group record using groupId and userId
 * @param {string} openGroupId
 * @param {int} userId
 * @return {object} Group
 */
export const findAndJoin = async (openGroupId, userId, groupOwnerId = 0) => {
  return sequelize.transaction(async t => {
    let group = await Group.findOne(
      {
        where: { openGroupId }
      },
      { transaction: t }
    )
    if (!group) {
      group = await Group.create(
        {
          openGroupId,
          ownerId: groupOwnerId
        },
        { transaction: t }
      )
    }
    let user = await User.findById(userId, { transaction: t })
    if (user == null) {
      throw new Error(`${ERRORS.DBERR.ERR_RECORD_NOT_FOUND}`)
    }
    let userGroup = await UserGroup.findOne(
      {
        where: { userId, groupId: group.id }
      },
      { transaction: t }
    )
    // let task = null
    // if (taskId) {
    //   task = await Task.findById(taskId, { transaction: t })
    //   if (task && !task.groupId) {
    //     task.groupId = group.id
    //     await task.save({ transaction: t })
    //   }
    // }
    if (userGroup == null) {
      //      let userRole = task && task.ownerId === userId ? 'admin' : 'user'
      let userRole = 'user'
      userGroup = await UserGroup.create(
        {
          userId: userId,
          groupId: group.id,
          role: userRole
        },
        { transaction: t }
      )
    }
    generateAvatar(group.id)
    return group
  })
}

/**
 * 查找自己的班级,只会查找自己是admin的群
 * @param {int} userId
 * @return {array} Groups
 */
export const findMyClasses = async ({ userId, pageIndex, pageSize }) => {
  const groups = await Group.findAndCountAll({
    where: {
      ownerId: userId,
      state: 'normal'
    },
    offset: pageIndex * pageSize,
    limit: pageSize
  })
  return groups
}

/**
 * 查找某个群里的某个学生
 * @param {int} groupId
 * @return {array} Users
 */
export const findGroupStudents = async (
  groupId,
  excludeIds = [],
  limit = 9
) => {
  let users = await User.findAll({
    where: {
      id: { $notIn: excludeIds }
    },
    include: [
      {
        model: Group,
        as: 'Groups',
        attributes: ['id'],
        where: { id: groupId }
      }
    ],
    limit
  })
  return users
}

/**
 * 获取组成员
 * @param  {Int}  groupId      组ID
 * @return {Promise}              [description]
 */
export const getMembers = async (groupId) => {
  let members = await fdb.findAll({
    tbl: 'user_group as ug',
    joins: [
      'left join users as u on u.id = ug.userId'
    ],
    attrs: [
      'ug.*, u.nickName, u.avatarUrl, u.gender'
    ],
    where: [
      `ug.groupId=${groupId}`
    ],
    orders: [
      `createdAt desc`
    ]
  })
  return members
}
